const lodash = require("lodash")
import Base from "../entities/Base"
import { dictToWhere } from '@/utils/sqlUtils'
import { DictType, UsageScope } from "@/entities/Constant"

const RuleDao = {
    table: "rule",
    pageSize: Base.pageSize
}

RuleDao.initialForm = () => {
    return JSON.parse(JSON.stringify({
        id: 0,
        type: 0,
        platformId: "",
        usageScope: 0,
        codeRule: "{}",
        moduleId: "",
        enable: 1,
        sourceType: 0
    }))
}

RuleDao.fetchAll = async (dict) => {
    let whereSql = dictToWhere(dict)
    return await Base.fetchWhere(RuleDao.table, whereSql)
}

RuleDao.fetchPage = async (dict, page) => {
    let whereSql = dictToWhere(dict)
    return await Base.fetchPage(RuleDao.table, whereSql, page)
}

RuleDao.fetchById = async (id) => {
    const whereSql = "where id = " + id
    return await Base.fetchOne(RuleDao.table, whereSql)
}

RuleDao.codeRuleBySource = async (source) => {
    let whereDict = {
        sourceType: source.batch,
        type: DictType.Platform,
        usageScope: UsageScope.Spider,
        enable: 1,
    }
    let rule = await RuleDao.fetchOne(whereDict)
    if (lodash.isEmpty(rule) || lodash.isEmpty(rule.codeRule)) {
        return null
    }
    return JSON.parse(rule.codeRule)
}

RuleDao.fetchOne = async (dict) => {
    let whereSql = dictToWhere(dict)
    let objs = await Base.fetchWhere(RuleDao.table, whereSql, " limit 1 ")
    if (objs.length > 0) {
        return objs[0]
    }
    return null
}

RuleDao.fetchCount = async (dict, page) => {
    let count = await RuleDao.countWhere(dict)
    let datas = await RuleDao.fetchPage(dict, page)
    return { count, datas }
}

RuleDao.countWhere = async (dict) => {
    let whereSql = dictToWhere(dict)
    console.log("whereSql", whereSql)
    return await Base.countWhere(RuleDao.table, whereSql)
}

RuleDao.save = async (obj) => {
    return await Base.save(RuleDao.table, obj)
}

RuleDao.delete = async (id) => {
    return await Base.delete(RuleDao.table, id)
}


export { RuleDao }